﻿using System.Reflection;
using QQ2564874169.WebFx.Nancy.Responses;
using QQ2564874169.WebFx.Nancy.Web;

namespace WebDemo
{
    public abstract class AppApi : NancyWebApi
    {
        public AppUser User => Context.CurrentUser as AppUser;

        protected AppApi()
        {
            ActionBefore += VerifyLoginStatus;
        }

        private void VerifyLoginStatus(object sender, ActionBeforeEventArgs e)
        {
            var attr = e.Action.GetCustomAttribute<SetPermission>();
            attr = attr ?? e.Action.DeclaringType.GetCustomAttribute<SetPermission>();
            if (attr == null || attr.Permission == AppPermission.无限制)
                return;
            if (User == null)
                throw new NoLoginException(Request.Url.ToString());
        }

        public static JsonResponse Success(object data = null)
        {
            data = data ?? 0;
            return new JsonResponse(new { data });
        }

        public static JsonResponse Failure(string error, object data = null)
        {
            return new JsonResponse(new { error, data });
        }
    }
}